package com.qm.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 @author james
 @create 2021-04-08 16:03
 */
public class ObjectMapperUtil {

    //json与对象的转化  优化异常处理
    private static final ObjectMapper MAPPER = new ObjectMapper();

    //1.对象转化为JSON
    public static String toJSON(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            //检查异常，转化为运行时异常
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //2.JSON转化为对象  传递什么样的类型
    public static <T> T toObject(String json, Class<T> target) {
        try {
            return MAPPER.readValue(json, target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
